package leesoft.hub;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import leesoft.toolbox.ServletTool;
import leesoft.hub.actions.IAction;
import leesoft.hub.actions.SessionContext;

/**
 * Servlet implementation class Hub
 */
public class Hub extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Hub() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGetPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGetPost(request,response);
	}
	private void doGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String contextPath=request.getContextPath();
		String requestURI=request.getRequestURI();
		String requestServletName=request.getServletPath();
		String actionName=ServletTool.getActionName(requestURI, contextPath, requestServletName);
		
		if(actionName.equals("")){
			return;//do nothing
		}
		IAction action=(IAction)ServletTool.getActionProcessor(actionName);
		action.setRequest(request);
		action.setResponse(response);
	
		JSONObject json = JSONObject.fromObject(action.process(SessionContext.getInstance(request))); 
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/html;charset=UTF-8"); 
		response.getWriter().print(json);
		
	}

}
